package com.leyou.filter;

import com.leyou.constants.JwtConstants;
import com.leyou.dto.Payload;
import com.leyou.dto.UserDetails;
import com.leyou.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 实现对用户jti超时时间的的刷新
 * @author jshstart
 * @creat 2020-12-24 21:22
 */
@Slf4j
@Component
@Order
public class RefreshJwtFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.拿到cookie
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
        if (cookie==null){
            return chain.filter(exchange);
        }
        //2.拿到jwt
        String jwt = cookie.getValue();
        UserDetails userDetail = null;
        try {
            //3.拿到用户id
            Payload payload = jwtUtil.parseJwt(jwt);
            userDetail = payload.getUserDetail();
            //4.调用jwtutil刷新时间
            jwtUtil.refreshJwt(userDetail.getId());
            log.info("用户{}正在访问{}", userDetail.getUsername(), request.getURI().getPath());
        } catch (Exception e) {
         log.info("用户未登录");
        }
        return chain.filter(exchange);
    }
}
